// Handles updating elements with live lamport values and converting to fiat if user has a preferred fiat set
window.SOLANA_LIVE_RATES = null;
window.SOLANA_RATES_TTL = null;
window.SOLANA_RATES_URL = null;
window.SOLANA_RATES_USE_FIAT = null; // Set by page script. If not set, utils will default to SOL.

// Utility functions for converting and displaying fiat/sol
// These functions rely on the variables above being set correctly
function fiat_symbol(arg = null) {
    switch (arg.toString().toUpperCase().replace('SOL', '').replace('_', '').replace('-', '')) {
        case 'USD': return '$';
        case 'AUD': return 'A$';
        case 'EUR': return '€';
        case 'GBP': return '£';
        case 'CAD': return 'C$';
        default: ;
    }
    return '[?]';
}

function _get_rate() {
    if (!window.SOLANA_LIVE_RATES || typeof window.SOLANA_LIVE_RATES !== 'object') {
        console.error('Invalid window.SOLANA_LIVE_RATES:', window.SOLANA_LIVE_RATES);
        return null;
    }
    // Get rate for user's preferred fiat
    if (window.SOLANA_LIVE_RATES[window.SOLANA_RATES_USE_FIAT] && !isNaN(window.SOLANA_LIVE_RATES[window.SOLANA_RATES_USE_FIAT])) {
        return window.SOLANA_LIVE_RATES[window.SOLANA_RATES_USE_FIAT] * 1;
    }
    // Check if rate is available for SOL[fiat]
    if (window.SOLANA_LIVE_RATES[`SOL${window.SOLANA_RATES_USE_FIAT}`] && !isNaN(window.SOLANA_LIVE_RATES[`SOL${window.SOLANA_RATES_USE_FIAT}`])) {
        return window.SOLANA_LIVE_RATES[`SOL${window.SOLANA_RATES_USE_FIAT}`] * 1;
    }
    // Check if rate is available for SOL_[fiat]
    if (window.SOLANA_LIVE_RATES[`SOL_${window.SOLANA_RATES_USE_FIAT}`] && !isNaN(window.SOLANA_LIVE_RATES[`SOL_${window.SOLANA_RATES_USE_FIAT}`])) {
        return window.SOLANA_LIVE_RATES[`SOL_${window.SOLANA_RATES_USE_FIAT}`] * 1;
    }
    return null;
}

function update_lamport_elements() {
    // Check if window.SOLANA_LIVE_RATES is defined and if user's preferred fiat is available

    $('.live_lamports').each(function() {
        try {
            // Get lamports from data-lamports attribute and convert to sol
            const lamports = parseInt($(this).attr('data-lamports'));
            const sol = lamports / 1000000000;
            const sol_str = `${sol} SOL`;
            const sol_rate = _get_rate();
            if (!sol_rate) {
                // Create a value string without trailing zeros
                $(this).empty().append(`<span style="font-weight:600;">${sol_str}</span>`);
                return;
            }
            // Convert to fiat
            const fiat = sol * sol_rate;
            const fiat_locale_fixed = fiat.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 });
            // Update element
            $(this).empty().append(`<span style="font-weight:600;">${fiat_symbol(window.SOLANA_RATES_USE_FIAT)}${fiat_locale_fixed}</span>`);
            if ($(this).hasClass('show_sol')) {
                $(this).append(`&nbsp;&nbsp;<span style="opacity:0.3;font-weight:300;">|</span>&nbsp;&nbsp;<span style="font-weight:300;">${sol_str}</span>`);
            }
        } catch (e) {
            console.error('Error updating live lamport element:', e);
        }
    });
}

function update_solana_rates() {
    fetch(window.SOLANA_RATES_URL)
        .then(response => response.json())
        .then(data => {
            try {
                window.SOLANA_LIVE_RATES = data?.rates || {};
                window.SOLANA_RATES_TTL = data?.ttl || 120; // seconds
                window.SOLANA_RATES_TTL = window.SOLANA_RATES_TTL * 1000; // convert to milliseconds
                update_lamport_elements();
                setTimeout(() => {
                    update_solana_rates();
                }, window.SOLANA_RATES_TTL);
            } catch (e) {
                console.error('Error updating window.SOLANA_LIVE_RATES:', e);
            }
        });
}

function init_live_lamports(rates_url = '/static/rates.json') {
    window.SOLANA_RATES_URL = rates_url;
    const user_fiat = $('#user_preferred_fiat').val();
    if (user_fiat && typeof user_fiat === 'string' && user_fiat.trim().length > 0) {
        window.SOLANA_RATES_USE_FIAT = user_fiat.trim();
    }
    update_solana_rates();
}

function fiat_to_lamports(fiat_val = 0) { // Use window.SOLANA_RATES_USE_FIAT to convert fiat to lamports 
    let lamports = 0;
    const rate = _get_rate();
    if (rate) {
        lamports = Math.floor(fiat_val / rate * 1e9);
    }
    return lamports;
}

function my_fiat_symbol() {
    return fiat_symbol(window?.SOLANA_RATES_USE_FIAT || null).toString();
}

function my_fiat_code() {
    return (window?.SOLANA_RATES_USE_FIAT || 'None').toString().toUpperCase().replace('SOL', '').replace('_', '').replace('-', '');
}